package com.sq.partner.manager.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayNocarBase;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayCustomerService;
import com.sq.partner.manager.service.IGatewayLifePolicyListService;
import com.sq.partner.manager.service.IGatewayNocarPolicyListService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value = "/nocarPolicyList")
public class NocarPolicyListController {
	
	private static Logger logger = LogUtil.getLog(NocarPolicyListController.class);
	
	@Resource
	private IGatewayLifePolicyListService lifePolicyListService;

	@Resource
	private IGatewayNocarPolicyListService nocarPolicyListService;

	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayProductService productService;
	
	@Resource
	private IGatewayCustomerService customerService;
	
	@Resource
	private INlifeProdConfigService nlifeProdConfigService;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model){
		List<DictDto> prodTypeList = DictCache.getProdType("2");	//查询所有财险产品类型
		model.addAttribute("prodTypeList", prodTypeList);
		return "transManager/nocarPolicyList";
	}
	
	/**
	 * 查询当前用户的权限机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(lifePolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		return Result.fail();
    }
	
	/**
	 * 查询传入机构及其子机构
	 * @param size
	 * @param pageIndex
	 * @param deptCode
	 * @param deptCNname
	 * @param parentCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDeptByDeptAndParentDeptCode",method = RequestMethod.POST)
	@ResponseBody
	public Page<CoreDept> queryDeptByDeptAndParentDeptCode(Integer size,Integer pageIndex,
				String deptCode,String deptCname,String parentDeptCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCname);
		page.setType(dept);

		return lifePolicyListService.queryDeptPageByDeptAndParentDeptCode(page, parentDeptCode);
	}
	
	/**
	 * 查询人险相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfoOfLife",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size,Integer pageIndex,
									String parentDeptCode,String channelName,String channelCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(parentDeptCode);
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return lifePolicyListService.queryChannelInfoPageOfLife(page);
	}
	
	/**
	 * 查询人险相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/querySubChannelTree",method = RequestMethod.POST)
	@ResponseBody
	public List<TreeDto> querySubChannelTree(String parentChannelCode) throws Exception{
		if(StrUtil.isEmpty(parentChannelCode)){
			throw new AppException("合作伙伴代码不能为空");
		}
		
		return lifePolicyListService.querySubChannelTreeByParentChannelCode(parentChannelCode);
	}
	
	/**
	 * 分页条件查询财险保单
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryNocarPolicyPageByCriteria")
	@ResponseBody
    public Page queryNocarPolicyPageByCriteria(HttpSession session, Integer pageIndex,
    			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
    			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception {
		
		@SuppressWarnings("rawtypes")
		Page page = beforeQueryNocarPolicyPageByCriteria(session, pageIndex, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);
		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
			return page;
		}
		return nocarPolicyListService.queryNocarPolicyPageByCriteria(page);
    }
	/**
	 * 汇总展示
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryNocarPolicyAll")
	@ResponseBody
	public Map<String,Object> queryNocarPolicyAll(HttpSession session, Integer pageIndex,
			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception {
		
		@SuppressWarnings("rawtypes")
		Page page = beforeQueryNocarPolicyPageByCriteria(session, pageIndex, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);
		 Map<String,String> map = (Map<String, String>) page.getType();
		return nocarPolicyListService.queryNocarPolicyAll(map);
	}
	
	/**
	 * 下载财险保单信息
	 * @param session
	 * @param response
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @throws Exception
	 */
	@RequestMapping(value = "/downloadNocarPolicyFileByCriteria")
    public void downloadNocarPolicyFileByCriteria(HttpSession session,HttpServletResponse response, 
    			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
    			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception {
		
		Page page = beforeQueryNocarPolicyPageByCriteria(session, -1, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);
		
		Map<String,Object> map = (Map<String, Object>) page.getType();
		List<Map<String, Object>> nocarPolicyList = nocarPolicyListService.queryNocarPolicyListByCriteria(map);
		nocarPolicyListService.downloadNocarPolicyFile(nocarPolicyList, response);
    }
	
	
	/**
	 * 财险保单查询和保单信息下载前进行验证
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	public Page beforeQueryNocarPolicyPageByCriteria(HttpSession session, Integer pageIndex,
			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		
		String dptCode = policy.getDptCde();
		String dptCodeStr = "";
		
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		map.put("privilegeBranch",privilegeBranch);
		
		map.put("dptCode", policy.getDptCde());
		
	/*	String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		if(StrUtil.isEmpty(polSubDateBegin) && StrUtil.isEmpty(polSubDateEnd)&& StrUtil.isEmpty(policy.getPolno())){
			page.setResult("error");
			page.setMessage("查询时保单号或保单提交日期必填其一");
			return page;
		}else if(StrUtil.isEmpty(polSubDateBegin) && StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateBegin = getAssignedDateStr(polSubDateEnd, 3);
		}else if(StrUtil.isNotEmpty(polSubDateBegin) && StrUtil.isEmpty(polSubDateEnd)){
			polSubDateEnd = getAssignedDateStr(polSubDateBegin, -3);
		}else if(StrUtil.isNotEmpty(polSubDateBegin) && StrUtil.isNotEmpty(polSubDateEnd)){
			//判断起止日期跨度是否超过3个月，超过true
			if(if2DateIntervalOverAssignedMonth(polSubDateBegin, polSubDateEnd, 3)){
				page.setResult("error");
				page.setMessage("保单提交日期跨度不能超过3个月");
				return page;
			}
		}*/
	
		//保单提交日期
		if(StrUtil.isNotEmpty(polSubDateBegin)){
			polSubDateBegin = polSubDateBegin + "00:00:00";
		}
		if(StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateEnd = polSubDateEnd + "23:59:59";
		}
		
		map.put("polSubDateBegin", polSubDateBegin);
		map.put("polSubDateEnd", polSubDateEnd);
		
		//保单生效日期
		if(StrUtil.isNotEmpty(polBeginDateBegin)){
			polBeginDateBegin = polBeginDateBegin + " 00:00:00";
		}
		if(StrUtil.isNotEmpty(polBeginDateEnd)){
			polBeginDateEnd = polBeginDateEnd + " 23:59:59";
		}
		
		map.put("polBeginDateBegin", polBeginDateBegin);
		map.put("polBeginDateEnd", polBeginDateEnd);
		
		
		//合作伙伴代码
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(privilegeBranch);
		List<Map> channelInfoList = nocarPolicyListService.queryChannelListOfNocar(channelInfo,"nocar");
		if(null == channelInfoList || channelInfoList.size() == 0){
			page.setResult("noChannelInfo");
			return page;
		}
		
		String channelCodeStr;
		if(StrUtil.isEmpty(policy.getPartnerNo())){
			channelCodeStr = "";
		}else{
			List<String> channelCodeList = new ArrayList<String>();
			for (Map m : channelInfoList) {
				channelCodeList.add(m.get("CHANNELCODE").toString());
			}
			if(!channelCodeList.contains(policy.getPartnerNo())){
				page.setResult("error");
				page.setMessage("合作伙伴["+policy.getPartnerNo()+"]没有权限执行此操作");
				return page;
			}
			channelCodeStr="'"+policy.getPartnerNo()+"'";
		}	
		map.put("channelCodeStr", channelCodeStr);
		map.put("isHq", 'N');
		//合作伙伴子机构
		if(StrUtil.isNotEmpty(policy.getPartnerSubCode()) && StrUtil.isEmpty(policy.getPartnerNo())){
			page.setResult("error");
			page.setMessage("合作伙伴子机构不为空，合作伙伴不允许为空");
			return page;
		}
		if("00".equals(privilegeBranch)){
			map.put("isHq", 'Y');
		}else {
			map.put("isHq", 'N');
		}
		map.put("partnerSubCode", policy.getPartnerSubCode());
		
		map.put("polno", policy.getPolno());
		map.put("stateId", policy.getStateId());
		map.put("orderId", policy.getOrderId());
		map.put("tradProdType", policy.getTradProdType());
		map.put("spical1", policy.getSpical1());
		map.put("tbrName", tbrName);
		map.put("tbrId", tbrId);
		map.put("bbrName", bbrName);
		page.setType(map);
		return page;
	}
	
	
	//转换成sql  in 字符串（格式为 'a','b','c'）
	public String transList2InStr(List<String> list){
		StringBuffer sb = new StringBuffer("'");
		if(null == list && list.size() == 0){
			return "''";
		}
		for (String string : list) {
			sb.append(string+"','");
		}
		
		return sb.substring(0, sb.length()-2);
	}
	
	
	/**
	 * 根据传入的日期字符串("yyyy-MM-dd")，得到该日期之前assignedMonth个月份的日期字符串（assignedMonth为负数时指之后月份的日期字符串）
	 * @param dateStr
	 * @param assignedMonth
	 * @return
	 * @throws Exception
	 */
	public String getAssignedDateStr(String dateStr,int assignedMonth) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			logger.info("日期格式不正确",e);
			throw new AppException("日期格式不正确");
		}
		
		date.setMonth(date.getMonth() - assignedMonth);
		
		return sdf.format(date);
	}
	
	/**
	 * 判断两个时间间隔是否超过指定月份(超过返回true)--传入字符串格式（yyyy-MM-dd）
	 * @param dateBeginStr
	 * @param dateEndStr
	 * @param assignedMonth
	 * @return
	 * @throws AppException
	 */
	public boolean if2DateIntervalOverAssignedMonth(String dateBeginStr,String dateEndStr,int assignedMonth) throws AppException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		Date dateBegin;
		Date dateEnd;
		try {
			dateBegin = sdf.parse(dateBeginStr);
			dateEnd = sdf.parse(dateEndStr);
		} catch (ParseException e) {
			logger.info("日期格式不正确",e);
			throw new AppException("日期格式不正确");
		}
			
		dateBegin.setMonth(dateBegin.getMonth() + assignedMonth);
		
		return !dateBegin.after(dateEnd);
	}
	
	//added by gzz@20151105 for shen zhen you hua begin 
	@RequestMapping(value = "/queryViewDetail", method = RequestMethod.POST)
	@ResponseBody public Page<Map<String, Object>> queryByTradNoticeId(String polNo,String tradProdType) throws Exception {
		Page<Map<String, Object>> page = new Page<Map<String,Object>>();
		if(StrUtil.isEmpty(polNo) /*|| StrUtil.isEmpty(tradProdType)*/){
			page.setResult("error");
			page.setMessage("请求参数错误，请稍后重试！");
			return page;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 逻辑处理思路：根据 产品类型进入相应的分支
		//1.根据保单号查询保单的相关信息
		//2.查询投被保人相关信息
		//3.查询受益人信息
		//4.查询险种信息
		GatewayPolicy policyInfo = nocarPolicyListService.queryPolicyInfoByPolNo(polNo);//1.
		DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern("###,###,###,###,###,###.00");
        if(null!=policyInfo && null!=policyInfo.getAmount()){
        	policyInfo.setAmountFormatStr(df.format(policyInfo.getAmount()));
        } 
        if(null!=policyInfo && null!=policyInfo.getPremium()){
        	policyInfo.setPremiumFormatStr(df.format(policyInfo.getPremium()));
        }
		//非即时起保保单保险止期应该是数据库所存日期的24:00:00
        if(null!=policyInfo && null!=policyInfo.getEndDateStr()){
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    		String endDateStr = policyInfo.getEndDateStr();
    		policyInfo.setEndDateStr(sdf.format(sdf.parse(endDateStr)));
        }
        GatewayNocarBase  gatewayNocarBase=	null;
        /**查询保险人信息*/
        if(null!=policyInfo && StrUtil.isNotEmpty(policyInfo.getPolicyId())){
          gatewayNocarBase=	nocarPolicyListService.queryNocarBaseByPolicyId(policyInfo.getPolicyId());
        
        }
        /* 
         * 增加下载OFD 和 到账证明的逻辑
         * */
		String OFDUrl = "";
		String proofUrl = "";
        //截取获取产品类型
        if(polNo.length() == 22) {
        	String prodType = polNo.substring(12,16);
	        if(null != policyInfo 
	        		&&
	        	Config.getProp("OFDFileDownloadUrlProd").contains(prodType)){
	        	Map<String,String> OFDInfoMap =  nocarPolicyListService.queryOFDAndProofDownloadUrl(policyInfo.getPolicyId());
	        	if(OFDInfoMap.size() > 0){
	        		//有数据 再继续
	        		try{
	        			OFDUrl = OFDInfoMap.get("OFDFILEURL");
		        		proofUrl = OFDInfoMap.get("PROOFFILEURL");
	        		}catch(NullPointerException e){
	        			OFDUrl = "";
		        		proofUrl = "";
	        			e.printStackTrace();
	        		}
	        	}
	        }
        }
       
        
    	map.put("gatewayNocarBase", gatewayNocarBase);
		map.put("policy_detail_Info", policyInfo);
		map.put("OFDUrl", OFDUrl);
		map.put("proofUrl", proofUrl);
		
		page.setObj(map);
		return page;
	}
	
	@RequestMapping(value = "/downloadTeamPolicyBBRInfoFileByPolNo",method = RequestMethod.POST)
    public void downloadTeamPolicyBBRInfoFileByPolNo(String polNo,HttpServletResponse response) throws Exception {
		if(StrUtil.isNotEmpty(polNo)){
			lifePolicyListService.downloadLifeTeamPolicyBBRInfoList(polNo, response);
		}else{
			logger.info("非法参数polNo（空值）传入，清单下载保单号不能为空");
		}
    }
	
	//added by gzz@20151105 for shen zhen you hua end
	@RequestMapping(value = "/reSendEmail", method = RequestMethod.POST)
	@ResponseBody
	public Result reSendEmail(String polNo,String email) throws Exception {
		logger.info("邮件重发： polNo: "+polNo+" 邮箱地址："+email);
		if(StrUtil.isEmpty(polNo)){
			return Result.fail("参数有误");
		}
		if(StrUtil.isEmpty(email)){
			return Result.fail("邮箱不能为空");
		}
		return nocarPolicyListService.addEmailReSend(polNo, email);
	}
	
	@RequestMapping(value = "/reSendSms", method = RequestMethod.POST)
	@ResponseBody
	public Result reSendSms(String polNo,String phoneNo) throws Exception {
		logger.info("短信重发： polNo: "+polNo+" 邮箱地址："+phoneNo);
		if(StrUtil.isEmpty(polNo)){
			return Result.fail("参数有误");
		}
		if(StrUtil.isEmpty(phoneNo)){
			return Result.fail("手机号不能为空");
		}
		return nocarPolicyListService.addSMSReSend(polNo, phoneNo);
	}
}
